package com.hamster.crmpre.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hamster.crmpre.config.LoginInterceptor;
import com.hamster.crmpre.mapper.*;
import com.hamster.crmpre.pojo.*;
import com.hamster.crmpre.pojo.dto.ChangeCourseDTO;
import com.hamster.crmpre.pojo.dto.ChangeCourseDTOParent;
import com.hamster.crmpre.service.CourseDetailsService;
import com.hamster.crmpre.service.PhoneUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 课程明细的Service
 * @author Tarry
 * @create 2019/12/28 11:03
 */
@Service
public class CourseDetailsServiceImpl implements CourseDetailsService {
    @Autowired
    private PhoneUserService phoneUserService;
    @Autowired
    private CustomerCourseClassMapper customerCourseClassMapper;
    @Autowired
    private CourseTimeMapper courseTimeMapper;
    @Autowired
    private CustomerCourseClassTimeMapper customerCourseClassTimeMapper;
    @Autowired
    private ProjectCourseMapper projectCourseMapper;
    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private PersonalMessageMapper personalMessageMapper;
    @Autowired
    private MessageChangeCourseMapper messageChangeCourseMapper ;


    /**
     * 查询客户课程明细
     * @param currentDate 日期
     * @param customerId  客户id
     * @return
     */
    @Override
    public List<CustomerCourseClass> getCourseDetails(Date currentDate, String customerId) {
        long time = currentDate.getTime(); // 当天开始的时间
        long day = 1 * 24 * 60 * 60 * 1000; //1天的时间
        time += day; // 相加得到新的毫秒数
        Date newDate = new Date(time);// 第二天开始的时间

        QueryWrapper<CustomerCourseClass> customerCourseClassQueryWrapper = new QueryWrapper<>();
        customerCourseClassQueryWrapper.eq("customer_id",customerId);
        List<CustomerCourseClass> courseClassList = customerCourseClassMapper.selectList(customerCourseClassQueryWrapper);
       for (CustomerCourseClass customerCourseClass : courseClassList) {
           QueryWrapper<CustomerCourseClassTime> customerCourseClassTimeQueryWrapper = new QueryWrapper<>();
           customerCourseClassTimeQueryWrapper.ge("start_time",currentDate).lt("start_time",newDate);
           customerCourseClassTimeQueryWrapper.eq("course_class_id",customerCourseClass.getId());
            List<CustomerCourseClassTime> customerCourseClassTimes = customerCourseClassTimeMapper.selectList(customerCourseClassTimeQueryWrapper);
            customerCourseClass.setTimeList(customerCourseClassTimes);
        }

        return courseClassList;
    }

    /**
     * 获取该客户的 全部课程明细
     * @param customerId
     * @return
     */
    @Override
    public List<CustomerCourseClass> getChangeCourseDetails(String customerId) {
        QueryWrapper<CustomerCourseClass> customerCourseClassQueryWrapper = new QueryWrapper<>();
        customerCourseClassQueryWrapper.eq("customer_id",customerId);
        List<CustomerCourseClass> courseClassList = customerCourseClassMapper.selectList(customerCourseClassQueryWrapper);

        for (CustomerCourseClass customerCourseClass : courseClassList) {
            QueryWrapper<CustomerCourseClassTime> customerCourseClassTimeQueryWrapper = new QueryWrapper<>();
            customerCourseClassTimeQueryWrapper.eq("course_class_id",customerCourseClass.getId());
            List<CustomerCourseClassTime> customerCourseClassTimes = customerCourseClassTimeMapper.selectList(customerCourseClassTimeQueryWrapper);
            customerCourseClass.setTimeList(customerCourseClassTimes);
        }
        return courseClassList;
    }

    /**
     * 保存客户详情明细
     * @param courseDetails 客户课程明细
     */
    @Override
    public void saveCourseDetails(List<CustomerCourseClass> courseDetails) {

        //版本1.0
        for (CustomerCourseClass courseDetail : courseDetails) {
            List<CustomerCourseClassTime> timeList = courseDetail.getTimeList();//获取该课程所有的上课时间对象
            for (CustomerCourseClassTime customerCourseClassTime : timeList) {
                customerCourseClassTimeMapper.updateById(customerCourseClassTime);
            }
        }

    }

    @Override
    public void saveCourseDetails2(List<CustomerCourseClassTime> timeList) {
        //版本 2.0
        for (CustomerCourseClassTime customerCourseClassTime : timeList) {
            customerCourseClassTimeMapper.updateById(customerCourseClassTime);
        }

    }

    /**
     * 更改客户课程
     * @param changeCourseDTOParent 预更改的课程内容 实体类
     */
    @Transactional
    @Override
    public void changeCourse(ChangeCourseDTOParent changeCourseDTOParent) {
        String customerId = changeCourseDTOParent.getCustomerId();
        String remark = changeCourseDTOParent.getRemark();
        //目标课程的id
        String targetCourseId = changeCourseDTOParent.getTargetCourseId();
        //目标课程的名称
        ProjectCourse projectCourse = projectCourseMapper.selectById(targetCourseId);
        String targetCourseTitle = projectCourse.getTitle();


        for (ChangeCourseDTO changeCourseDTO : changeCourseDTOParent.getCourseList()) {
            //如果projectId为空，或者课时列表为空  直接 continue
            if (StringUtils.isBlank(changeCourseDTO.getProjectId()) || changeCourseDTO.getSelectedCourseTime() == null){
                continue;
            }
            //直接更改，改完后，给财务发个通知就行，不用审核【这里暂时不做 课程更改记录统计】
            //1.获取目标课程对象包含的课程，给其客户添加 目标课程
            CustomerCourseClass customerCourseClass = new CustomerCourseClass();
            customerCourseClass.setCustomerId(customerId);
            customerCourseClass.setCourseTitle(targetCourseTitle);
            customerCourseClass.setCourseId(targetCourseId);
            customerCourseClass.setProjectId(changeCourseDTO.getProjectId());
            customerCourseClassMapper.insert(customerCourseClass);
            String classId = customerCourseClass.getId();//获取刚刚的 id
            //查询课程的课时，添加到课时表
            List<CourseTime> courseTimes = courseTimeMapper.queryListByCourseId(targetCourseId);
            //给用户课时表，插入对应该课程的课时
            for (CourseTime courseTime : courseTimes) {
                CustomerCourseClassTime customerCourseClassTime = new CustomerCourseClassTime();
                customerCourseClassTime.setCourseClassId(classId);
                customerCourseClassTime.setStartTime(courseTime.getStartTime());
                customerCourseClassTime.setEndTime(courseTime.getEndTime());
                customerCourseClassTime.setState("0");
                customerCourseClassTimeMapper.insert(customerCourseClassTime);
            }

            //2.删除原来选中的课程的课时
            List<String> selectedCourseTimeIds = changeCourseDTO.getSelectedCourseTime();
            customerCourseClassTimeMapper.deleteBatchIds(selectedCourseTimeIds);

            //3.将结果通知财务
            MessageChangeCourse messageChangeCourse = new MessageChangeCourse();
            messageChangeCourse.setContent(targetCourseTitle);
            messageChangeCourse.setCustomerId(customerId);
            Customer customer = customerMapper.selectById(customerId);
            messageChangeCourse.setCustomerName(customer.getName());
            messageChangeCourse.setCustomerPhone(customer.getPhone());
            messageChangeCourse.setRemark(remark);
            messageChangeCourseMapper.insert(messageChangeCourse);//插入消息详情
            String linkId = messageChangeCourse.getId();//获取详情的id
            PersonalMessage personalMessage = new PersonalMessage();
            personalMessage.setMessageLink(linkId);//详情的id
            personalMessage.setMessageType("更换课程");//消息类型
            personalMessage.setReceiverName("财务部");
            personalMessage.setReceiverId("财务部");
            personalMessage.setDepartment("财务部");
            personalMessage.setCreateTime(new Date());
            personalMessage.setState("0");
            String userName = phoneUserService.queryNameByPhone(LoginInterceptor.getLoginUser().getPhone());
            personalMessage.setSenderName(userName);//发送者姓名
            personalMessage.setSenderId(LoginInterceptor.getLoginUser().getUserId());//发送者id
            personalMessageMapper.insert(personalMessage);//插入消息中心

        }
    }

    /**
     * 更改课程页面，
     * 获取课程的select
     * @return
     */
    @Override
    public List<ProjectCourse> getCourseSelect() {
        QueryWrapper<ProjectCourse> projectCourseQueryWrapper = new QueryWrapper<>();
        projectCourseQueryWrapper.select("id","title");
        projectCourseQueryWrapper.eq("del","0");
        return   projectCourseMapper.selectList(projectCourseQueryWrapper);
    }


}
